package org.jeecg.common.util;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <B>系统名称：</B><BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B><BR>
 * <B>概要说明：</B><BR>
 *
 * @author 中科软科技
 * @since 2020/8/24
 */
public class DataUtils {


    /**
     * 处理数据保存位数
     * @param number 数字
     * @param precision 位数
     * @return
     */
    public static String keepPrecision(String number, int precision) {
        BigDecimal bg = new BigDecimal(number);
        return bg.setScale(precision, BigDecimal.ROUND_HALF_UP).toPlainString();
    }


    /**
     *  根据数据类型 获取不同的数据格式
     * @param number
     * @param type  1 四舍五入  2 向下取整  3 向上取整
     * @return
     */
    public static String getNumber(String number,String type){
        String sum = "";
        if(CommonConstant.STATUS_1.equals(type)){
            long num  = Math.round(Double.valueOf(number));
            sum = String.valueOf(num);
        }else if(CommonConstant.STATUS_2.equals(type)){
            double   num = Math.floor(Double.valueOf(number));
            sum = String.valueOf(num).substring(0,String.valueOf(num).indexOf("."));
        }else if(CommonConstant.STATUS_3.equals(type)){
            double   num =  Math.ceil(Double.valueOf(number));
            sum = String.valueOf(num).substring(0,String.valueOf(num).indexOf("."));
        }
        return sum;
    }


    public static final String DEFAULT_QUERY_REGEX = "[!$^&*+=|{}';'\",<>/?~！#￥%……&*——|{}【】‘；bai：”“'。，、？]";
    /**
     * 判断查询参数中是否以特殊字符开头，如果以特殊字符开头则返回true，否则返回false
     *
     * @param value
     * @return
     * @see {@link #getQueryRegex()}
     * @see {@link #DEFAULT_QUERY_REGEX}
     */
    public static boolean specialSymbols(String value) {
        if (StringUtils.isBlank(value)) {
            return false;
        }
        Pattern pattern = Pattern.compile(getQueryRegex());
        Matcher matcher = pattern.matcher(value);
        char[] specialSymbols = getQueryRegex().toCharArray();
        boolean isStartWithSpecialSymbol = false; // 是否以特殊字符开头
        for (int i = 0; i < specialSymbols.length; i++) {
            char c = specialSymbols[i];
            if (value.indexOf(c) == 0) {
                isStartWithSpecialSymbol = true;
                break;
            }
        }
        return matcher.find() && isStartWithSpecialSymbol;
    }
    /**
     * 获取查询过滤的非法字符
     *
     * @return
     */
    protected static String getQueryRegex() {
        return DEFAULT_QUERY_REGEX;
    }

    public static void main(String[] args) {
      String code =  keepPrecision("100",0);
      System.out.println(code);
      System.out.println(getNumber(keepPrecision("100.001",0),"1"));
    }
}
